package com.pks.datacenter.controller.basic;

import io.swagger.annotations.Api;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.ohedu.base.model.UserModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.pks.datacenter.aspect.AspectLogTag;
import com.pks.datacenter.config.MyConfig;
import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.entity.basic.DbField;
import com.pks.datacenter.entity.basic.DbInfo;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.service.api.ApiFieldService;
import com.pks.datacenter.service.basic.DbFieldService;
import com.pks.datacenter.service.basic.DbInfoService;
import com.pks.datacenter.service.basic.JobInfoService;
import com.pks.resultful.common.SRemoteResult;
import com.pks.util.UtilConvert;
import com.pks.util.UtilString;
import com.pks.utils.poi.SExcelUtil;
import com.pks.web.dto.ServiceResult;
import com.pks.web.springmvc.controller.BasicController;
import com.thanone.base.common.Constant;
import com.thanone.base.common.DictionaryKeyConstant;

@RestController
@RequestMapping("/dbField")
@Scope("prototype")
@Component("dbFieldAction")
@Api(tags = "数据源字段")
public class DbFieldAction extends BasicController {

	@Resource
	private DbFieldService dbFieldService;
	@Resource
	private DbInfoService dbInfoService;
	@Resource
	private JobInfoService jobInfoService;
	@Resource 
	private ApiFieldService apiFieldService;
	@Resource
	private RedisHandler redisHandler;

	@RequestMapping("/tolist")
	public ModelAndView tolist(Model model,@RequestParam(required=true) Long dbId) {
		model.addAttribute("dbId", dbId);
		return new ModelAndView("/WEB-INF/ftl/admin/basic/dbfield_list");
	}

	@RequestMapping("/list")
	public SRemoteResult<List<DbField>> list(@RequestParam(required=true) Long dbId,String enName ,String enNameLike ,String chName ,String chNameLike ,Integer type) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		qbuilder.put("dbId", dbId);
		if (UtilString.isNotBlank(enName)) {
			qbuilder.put("enName", enName);
		}
		if (UtilString.isNotBlank(enNameLike)) {
			qbuilder.put("enNameLike", "%" + enNameLike.trim() + "%");
		}
		if (UtilString.isNotBlank(chName)) {
			qbuilder.put("chName", chName);
		}
		if (UtilString.isNotBlank(chNameLike)) {
			qbuilder.put("chNameLike", "%" + chNameLike.trim() + "%");
		}
		if (type != null) {
			qbuilder.put("type", type);
		}
		List<DbField> list = new ArrayList<DbField>();
		int total = 0;
		total = dbFieldService.getTotalRows(qbuilder);
		if(total > 0 ){
			list = dbFieldService.findByPage("orders asc ,id asc ", qbuilder);
		}
		return SRemoteResult.initPageList(list, total);
	}

	@RequestMapping("/toadd")
	public String toadd(Model model,@RequestParam(required=true) Long dbId) {
		model.addAttribute("dbId", dbId);
		return "/WEB-INF/ftl/admin/basic/dbfield_modify";
	}

	@RequestMapping("/tomodify")
	public ModelAndView tomodify(Long id, Model model,@RequestParam(required=true) Long dbId) {
		DbField obj = null;
		if(id!=null){
			obj = dbFieldService.findById(id);
		}
		model.addAttribute("obj", obj);
		model.addAttribute("dbId", dbId);
		return new ModelAndView("/WEB-INF/ftl/admin/basic/dbfield_modify");
	}
	
	@RequestMapping("/tobatchadd")
	public ModelAndView tobatchadd(Model model,@RequestParam(required=true) Long dbId){
		model.addAttribute("dbId", dbId);
		return new ModelAndView("/WEB-INF/ftl/admin/basic/dbfield_batchadd");
	}

	@RequestMapping("/delete")
	@AspectLogTag(operType = "删除")
	public SRemoteResult<String> delete(HttpServletRequest request, String ids,@RequestParam(required=true) Long dbId) {
		if (UtilString.isBlank(ids)) {
			return SRemoteResult.initError("请选择需要删除的记录！");
		}
		if(StringUtils.isBlank(ids) || !ids.matches("^[0-9]+(,[0-9]+)*$")){
			return SRemoteResult.initErrorParamInvalid("ids");
		}
//		if (jobInfoService.getTotalRows(jobInfoService.initQbuilder("dbused", dbId))>1){
//			return SRemoteResult.initError("该数据源已被任务处理使用，无法删除");
//		}
		List<Long> idList = UtilConvert.string2LongList(ids);
		if(idList.size() == 1){
			dbFieldService.delete(idList.get(0));
		}else{
			dbFieldService.deleteByIds(idList);
		}
		redisHandler.del(RedisKeyConfig.KEY_LIST_DBFIELD_PREFIX + dbId);
		return SRemoteResult.initSuccess(null);
	}
	
	@AspectLogTag(operType = "修改")
	@RequestMapping("/modify")
	public SRemoteResult<String> modify(HttpServletRequest request, Long id, DbField obj) {
		if (obj == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if(obj.getDbId()==null){
			return SRemoteResult.initErrorParamMissing("dbId");
		}
		if(jobInfoService.getTotalRows(jobInfoService.initQbuilder("dbused", obj.getDbId()))>1){
			return SRemoteResult.initError("该数据源已被使用，无法修改");
		}
		if(id==null){
			obj.setId(UtilString.getLongUUID());
			dbFieldService.insert(obj);
		}else{
			DbField update = dbFieldService.findById(id);
			if(update==null){
				return SRemoteResult.initErrorDataNone();
			}
			dbFieldService.update(obj);
		}
		redisHandler.del(RedisKeyConfig.KEY_LIST_DBFIELD_PREFIX + obj.getDbId());
		return SRemoteResult.initSuccess(null);
	}
	
	@SuppressWarnings("unused")
	@RequestMapping("/batchadd")
	public SRemoteResult<String> batchadd(HttpServletRequest request,Long dbId,String batchinfo){
		if(dbId==null){
			return SRemoteResult.initErrorParamMissing(null);
		}
		if(StringUtils.isBlank(batchinfo)){
			return SRemoteResult.initErrorParamMissing("字段信息为空");
		}
//		if(jobInfoService.getTotalRows(jobInfoService.initQbuilder("dbused", dbId))>1){
//			return SRemoteResult.initError("该数据源已被使用，无法修改");
//		}
		String[] list = batchinfo.split("\r\n");
		String regex = "^(.+)(--[123])$";			//字段名+类型
		String regex2 = "^(.+)(--[123])(--.+)$";	//字段名+类型+中文名
		String regex3 = "^(.+)(--[123])(--[\\d]{1,4})$";	//字段名+类型+排序号
		String regex4 = "^(.+)(--[123])(--.+)(--[\\d]{1,4})$";	//字段名+类型+中文名+排序号
		
		
		String[] temp ;
		List<DbField> fieldList = new ArrayList<DbField>();
		for (String s : list) {
			if(StringUtils.isBlank(s)){
				continue;
			}
			if(!s.matches(regex)){
				return SRemoteResult.initError(s+"格式不正确");
			}
			temp = s.split("--");
			DbField field = new DbField();
			field.insertBefore();
			field.setDbId(dbId);
			field.setEnName(temp[0]);
			field.setType(Integer.parseInt(temp[1]));
			if (temp.length >2) {
				field.setChName(temp[2]);
			}
			if (temp.length >3) {
				field.setOrders(Long.parseLong(temp[3]));
			}
			fieldList.add(field);
		}
		dbFieldService.inserts(fieldList);
		redisHandler.del(RedisKeyConfig.KEY_LIST_DBFIELD_PREFIX + dbId);
		return SRemoteResult.initSuccess(null);
	}

	@RequestMapping("/findInfo")
	public SRemoteResult<DbField> findInfo(HttpServletRequest request, Long id) {
		if(id==null){
			return SRemoteResult.initErrorParamMissing("id");
		}
		DbField obj = dbFieldService.findById(id);
		if(obj==null){
			return SRemoteResult.initErrorDataNone();
		}
		return SRemoteResult.initSuccess(obj);
	}
	
	@RequestMapping("/genFields")
	public SRemoteResult<?> genFields(HttpServletRequest request, @RequestParam(required=true) Long dbId) {
		ServiceResult result = dbFieldService.insertForGenByDb(dbId);
		if (result.success()) {
			redisHandler.del(RedisKeyConfig.KEY_LIST_DBFIELD_PREFIX + dbId);
		}
		return SRemoteResult.fromServiceResult(result);
	}

	@RequestMapping(value = "/data" , method = RequestMethod.POST)
	public SRemoteResult<List<DbField>> data(@RequestParam(required=true) Long dbId,String enName ,String enNameLike ,String chName ,String chNameLike ,Integer type) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		qbuilder.put("dbId", dbId);
		if (UtilString.isNotBlank(enName)) {
			qbuilder.put("enName", enName);
		}
		if (UtilString.isNotBlank(enNameLike)) {
			qbuilder.put("enNameLike", "%" + enNameLike.trim() + "%");
		}
		if (UtilString.isNotBlank(chName)) {
			qbuilder.put("chName", chName);
		}
		if (UtilString.isNotBlank(chNameLike)) {
			qbuilder.put("chNameLike", "%" + chNameLike.trim() + "%");
		}
		if (type != null) {
			qbuilder.put("type", type);
		}
		List<DbField> list = new ArrayList<DbField>();
		list = dbFieldService.find("orders asc ,id asc ", qbuilder,null);
		int total = list.size();
		return SRemoteResult.initPageList(list, total);
	}
	
	@RequestMapping(value="/exportDbFields")
	public SRemoteResult<Map<String, String>> exportDbFields(HttpServletRequest request, HttpServletResponse response, Long dbId) {
		if (dbId ==null) {
			return SRemoteResult.initErrorParamBlank("数据源编号");
		}
		DbInfo dbInfo = dbInfoService.findById(dbId);
		if (dbInfo == null) {
			return SRemoteResult.initError("数据源不存在");
		}
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		qbuilder.put("dbId", dbId);
		List<DbField> list = dbFieldService.find("orders asc , id asc ", qbuilder, null);
		if (list.size() == 0) {
			return SRemoteResult.initError("该数据源暂无字段信息");
		}
		try {
			String absoluteFile = MyConfig.getSavePath() + File.separator + "exceltemplate" + File.separator + "blanktemplate.xls";
//			String path = File.separator + "dbfield" + File.separator + UtilString.getUUID() + ".xls";
			String path = File.separator + "dbfield" + File.separator + dbId + ".xls";
			String downloadFile = MyConfig.savePath + path ;
			File file = new File(downloadFile);
			if (file.exists()) {
				file.delete();
			}
			SExcelUtil.getInstance().exportObj2ExcelByTemplate(null,absoluteFile, downloadFile, list, DbField.class, false,true);
//			SExcelUtil.getInstance().exportObj2ExcelByTemplate(null, absoluteFile, response.getOutputStream(), list, DbField.class, false,true); 
//			SExcelUtil.getInstance().exportObj2ExcelByTemplateHb(null,absoluteFile, downloadFile, list, DbField.class, false,true);
			
			Map<String, String> fileData = new HashMap<String, String>();
			fileData.put("filepath", path);
			fileData.put("fileName", dbInfo.getName() + "字段信息");
			return SRemoteResult.initSuccess(fileData);
//			out.write(ServiceResult.initSuccessJson(new DownloadResult(ExportExcelUserDto.filename_export, path)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SRemoteResult.initError("导出文件生成失败");
	}
	
	
	
	
	
}
